// 计算地面站覆盖范围包络图
import * as turf from '@turf/turf'
import * as DT from 'dt-sdk'
import { viewer } from '@/components/dt-scene/index.vue'
import Login from "@/views/login";
import { mapGetters } from "vuex";
let totalCoverEntities = []
let coverPrimitive, lineCoverPrimitive
export default {
  data() {
    return {
      totalStationCoverIds: 0,
      stationCoverAdd: false
    }
  },
  watch: {
    // isGlobalSatellite(nv) {
    //   if (coverPrimitive && viewer) {
    //     coverPrimitive.show = nv
    //   }
    //   if (lineCoverPrimitive && viewer) {
    //     lineCoverPrimitive.show = nv
    //   }
    //
    // }

  },
  beforeDestroy() {
    if (coverPrimitive && viewer) {
      viewer.primitives.remove(coverPrimitive)
      coverPrimitive = null
    }
    if (lineCoverPrimitive && viewer) {
      viewer.primitives.remove(lineCoverPrimitive)
      lineCoverPrimitive = null
    }
  },
  ...mapGetters([
    // 'switch',
    'isGlobalSatellite',
  ]),
  methods: {
    hiddenCoverArea() {
        if (coverPrimitive && viewer) {
          coverPrimitive.show = false
        }
        if (lineCoverPrimitive && viewer) {
          lineCoverPrimitive.show = false
        }
    },
    initDataDraw(dataArr) {
      // 全部的turf circle对象
      let turfObjArr = []
      for (let key in dataArr) {
        if (dataArr[key] && dataArr[key].visible && dataArr[key].data.length > 2) {
          let turfFeature = turf.polygon([dataArr[key].data])
          turfObjArr.push(turfFeature)
        }
      }
      if (turfObjArr.length === 0) {
        return
      }
      // dataArr.forEach(e => {
      //   let turfFeature = turf.polygon(e.coord, e.radius, {
      //     steps: 20,
      //     units: 'kilometers'
      //   })
      //   turfObjArr.push(turfFeature)
      // })

      // 判断两个两个圆是否相交
      let intersectCircle = []
      let len = turfObjArr.length
      if (len > 1) {
        for (let i = 0; i < len - 1; i++) {
          let result = [i]
          for (let j = i + 1; j < len; j++) {
            // 两个圆是否相交（相交返回true， 不想交返回false）
            let overlap = turf.booleanOverlap(turfObjArr[i], turfObjArr[j])
            // console.log(overlap)。
            if (overlap) {
              result.push(j)
            }
          }
          intersectCircle.push(result)
        }
      } else {
        intersectCircle.push([0])
      }

      if (intersectCircle.length > 0) {
        intersectCircle.push([len - 1])
      }
      // 去重
      if (intersectCircle.length > 0) {

      }
      let calcResult = [intersectCircle[0]]
      intersectCircle.forEach((item, index) => {
        if (index > 0) {
          let find = []
          for (let i = 0; i < calcResult.length; i++) {
            for (let j = 0; j < item.length; j++) {
              if (calcResult[i].indexOf(item[j]) !== -1) {
                find.push(i)
                break
              }
            }
          }
          if (find.length > 0) {
            let combin = [].concat(item)
            find.forEach(com => {
              combin = combin.concat(calcResult[com])
            })
            combin = [[...new Set(combin)]]
            calcResult.forEach((ddd, dd) => {
              if (find.indexOf(dd) === -1) {
                combin.push(ddd)
              }
            })
            calcResult = JSON.parse(JSON.stringify(combin))
          } else {
            calcResult.push(item)
          }
        }
      })
      intersectCircle = calcResult

      // 将数组扁平化处理
      // let modifyArr = intersectCircle.flat()
      // if (intersectCircle.length > 0) {
      //   modifyArr = intersectCircle.reduce(function(a, b) {
      //     return a.concat(b)
      //   })
      // }
      // 创建一个验证数组，查看那个数字没有在turfCircle里面
      // let verifyArr = []
      // for (let i = 0; i < dataArr.length; i++) {
      //   verifyArr.push(i)
      // }
      // if (this.getArrDifference(modifyArr, verifyArr).length > 0) {
      //   intersectCircle.push(this.getArrDifference(modifyArr, verifyArr))
      // }

      let instances = []
      let lineInstances = []
      intersectCircle.forEach(e => {
        if (e.length > 1) {
          let elen = e.length
          let number1 = e[0]
          let number2 = e[1]
          let tempUnion = turf.union(turfObjArr[number1], turfObjArr[number2])

          for (let i = 2; i < elen; i = i + 1) {
            let numE = e[i]
            tempUnion = turf.union(tempUnion, turfObjArr[numE])
          }
          instances.push(this.createCoverGeometry(tempUnion.geometry.coordinates[0].flat(Infinity)))
          lineInstances.push(this.createCoverLineGeometry(tempUnion.geometry.coordinates[0].flat(Infinity)))
          // this.renderCircle(tempUnion.geometry.coordinates[0].flat(Infinity))
        } else {
          let number = e[0]
          instances.push(this.createCoverGeometry(turfObjArr[number].geometry.coordinates[0].flat(Infinity)))
          lineInstances.push(this.createCoverLineGeometry(turfObjArr[number].geometry.coordinates[0].flat(Infinity)))
          // this.renderCircle(
          //   turfObjArr[number].geometry.coordinates[0].flat(Infinity)
          // )
        }
      })
      if (instances.length > 0) {
        this.createCoverPrimitive(instances, lineInstances)
      }
    },
    getArrDifference(arr1, arr2) {
      return arr1.concat(arr2).filter(function (v, i, arr) {
        return arr.indexOf(v) === arr.lastIndexOf(v)
      })
    },
    createCoverGeometry(data) {
      let geometry = new DT.Cesium.GeometryInstance({
        geometry: new DT.Cesium.PolygonGeometry({
          polygonHierarchy: new DT.Cesium.PolygonHierarchy(DT.Cesium.Cartesian3.fromDegreesArray(data))
        }),
      });
      return geometry
    },
    createCoverLineGeometry(data) {
      let geometry = new DT.Cesium.GeometryInstance({
        geometry: new DT.Cesium.GroundPolylineGeometry({
          positions: DT.Cesium.Cartesian3.fromDegreesArray(data),
          width: 1.0
        }),
        // attributes : {
        //   color : DT.Cesium.ColorGeometryInstanceAttribute.fromColor(DT.Cesium.Color.fromCssColorString('#ff5143')),
        //   // distanceDisplayCondition : new Cesium.DistanceDisplayConditionGeometryInstanceAttribute(1000, 30000)
        // },
      });
      return geometry
    },
    createCoverPrimitive(instances, lineInstances) {
      let newCoverPrimitive = viewer.primitives.add(new DT.Cesium.GroundPrimitive({
        geometryInstances: instances,
        appearance: new DT.Cesium.MaterialAppearance({
          material: new DT.Cesium.Material.fromType('Color', {
            color: DT.Cesium.Color.fromCssColorString('green').withAlpha(0.3),
          }),
        }),
        asynchronous: false,
      }));
      if (coverPrimitive) {
        viewer.primitives.remove(coverPrimitive)
        coverPrimitive = null
      }
      coverPrimitive = newCoverPrimitive
      coverPrimitive.isCover = true
      if (this.hiddenCover) {
        coverPrimitive.show = false
      }
      let newLineCoverPrimitive = viewer.primitives.add(new DT.Cesium.GroundPolylinePrimitive({
        geometryInstances: lineInstances,
        appearance: new DT.Cesium.MaterialAppearance({
          material: new DT.Cesium.Material.fromType('Color', {
            color: DT.Cesium.Color.fromCssColorString('AQUA'),
          }),
        }),
        asynchronous: false,
      }));
      if (lineCoverPrimitive) {
        viewer.primitives.remove(lineCoverPrimitive)
        lineCoverPrimitive = null
      }
      lineCoverPrimitive = newLineCoverPrimitive
      lineCoverPrimitive.isCover = true
      if (this.hiddenCover) {
        lineCoverPrimitive.show = false
      }
      this.stationCoverAdd = true
    },
    renderCircle(data) {
      // console.log('计算数据', data);
      let entity = viewer.entities.add({
        polygon: {
          hierarchy: DT.Cesium.Cartesian3.fromDegreesArray(data),
          material: DT.Cesium.Color.fromCssColorString('#ff5143').withAlpha(0.3),
          clampToGround: true
        },
        polyline: {
          width: 1,
          positions: DT.Cesium.Cartesian3.fromDegreesArray(data),
          material: DT.Cesium.Color.fromCssColorString('#ff5143'),
          clampToGround: true
        }
      })
      this.totalStationCoverIds++
      totalCoverEntities.push(entity)
    },
    clearAllCoverArea() {
      if (coverPrimitive && viewer) {
        viewer.primitives.remove(coverPrimitive)
        coverPrimitive = null
      }
      if (lineCoverPrimitive && viewer) {
        viewer.primitives.remove(lineCoverPrimitive)
        lineCoverPrimitive = null
      }
      // totalCoverEntities.forEach(item => {
      //   viewer.entities.remove(item)
      // })
      this.stationCoverAdd = false
    }
  }
}
